package com.desire.homework;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LittleDesire
 * @description
 * @date 2022-02-09 周三 20:54
 * @since 17
 */
public class _51_多线程输出A1B2C3A4B5C6 {
    AtomicInteger num = new AtomicInteger(0);
    ReentrantLock lock = new ReentrantLock(true);

    public static void main(String[] args) {
        var t = new _51_多线程输出A1B2C3A4B5C6();
        var a = new Thread(t::work, "A");
        a.start();

        var b = new Thread(t::work, "B");
        b.start();

        var c = new Thread(t::work, "C");
        c.start();
    }

    void work() {
        String tn = Thread.currentThread().getName();
        while (true) {
            lock.lock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // num.incrementAndGet() 自增
            System.out.printf("%s%d  ", tn, num.incrementAndGet());
            // 3个后 打印换行
            if ("C".equals(tn)) {
                System.out.println();
            }
            lock.unlock();
        }
    }
}
